import { pathToRegexp } from 'path-to-regexp';
import { history } from 'umi'

export default {

  namespace: 'manageCenter',

  state: {
    lastManagePath: '',
    lastPathState: null
  },

  subscriptions: {
    setupHistory({ dispatch, history }) {  // eslint-disable-line
      return history.listen(({ pathname, state }) => {
        if (pathname === '/manageCenter') {
          dispatch({ type: "fetchLastManagePath" });
          return;
        }
        if (pathToRegexp('/manageCenter', [], { end: false }).exec(pathname)) {
          dispatch({ type: "save", payload: { lastManagePath: pathname, lastPathState: state } });
        }
      })
    },
  },

  effects: {
    *fetchLastManagePath(_, { select, put }) {
      const { lastManagePath, lastPathState } = yield select(_ => _.manageCenter);
      if (lastManagePath && window.location.pathname !== lastManagePath) { // 避免重复跳转到同一路径
        history.push({ pathname: lastManagePath, state: lastPathState });
        return;
      }
      if (!lastManagePath) {
        history.push({ pathname: '/manageCenter/articleManage' });
      }
    },
  },

  reducers: {
    save(state, action) {
      return { ...state, ...action.payload };
    },
  },
};